package com.archstoday.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import com.archstoday.R;
import com.archstoday.common.AsRes;
import com.archstoday.entity.ScreenEntity;
import com.archstoday.utils.BitmapUtil;
import com.archstoday.utils.ToolUtils;
import com.base.http.common.BaseHttpClient;
import com.base.http.utils.FileNameGenerator;
import com.base.utils.CropUtil;
import com.base.utils.LogUtil;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 启动页面
 */
public class StartActivity extends AsBaseActivity {

    private ScreenEntity mEntity;

    @Override
    protected void initView(Bundle bundle) {
        setContentView(R.layout.activity_start);
    }

    List<Bitmap> bitmapList;
    @Override
    protected void initData(Bundle bundle) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0x08);
        } else {
            upData();
            toActivity();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 0x08:
                upData();
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    toActivity();
                } else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent(mContext, MainActivity.class);
                            startActivity(intent);
                            appFinish();
                        }

                    }, 1000);
                    showToast("若要使用完整功能请打开sd卡权限！");
                }
                break;
        }
    }

    private void toActivity() {
        bitmapList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Bitmap bitmap = getBitmap(i + ".jpg");
            if (bitmap != null) {
                bitmapList.add(bitmap);
            }
            break;
        }
        if (bitmapList == null || bitmapList.size() == 0) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(mContext, MainActivity.class);
                    startActivity(intent);
                    appFinish();
                }

            }, 1000);
        } else {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    BitmapUtil.getInstance().setBitmapList(bitmapList);
                    Intent intent = new Intent(mContext, StartUpActivity.class);
                    startActivity(intent);
                    appFinish();
                }

            }, 1000);
        }
    }

    private void upData() {
        initParameter();
        mParams.put("selectType", "headerInitImg");

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.GET_SELECT_BASE),
                AsRes.GET_SELECT_BASE, mParams, ScreenEntity.class);
    }

    @Override
    protected void onSuccess(String content, BaseHttpClient client, Object parse) {
        if (client.getUrlIdentifier() == AsRes.GET_SELECT_BASE) {
            mEntity = (ScreenEntity) parse;
            if (ToolUtils.isSuccess(mEntity.getStatus())) {
                if (mEntity.getData() != null && mEntity.getData().size() > 0) {
                    String[] imgs = new String[mEntity.getData().size()];
                    for (int i = 0; i < mEntity.getData().size(); i++) {
                        imgs[i] = mEntity.getData().get(i).getLabel();
                    }

                    downloadImg(imgs);
                } else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent(mContext, MainActivity.class);
                            startActivity(intent);
                            appFinish();
                        }

                    }, 1000);
                }
            }
        }
    }

    private Bitmap[] bitmaps;

    private void downloadImg(final String[] urls) {
        bitmaps = new Bitmap[urls.length];
        // 为了下载图片资源，开辟一个新的子线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < urls.length; i++) {
                    // 下载图片的路径
                    String iPath = urls[i];
                    try {
                        // 对资源链接
                        URL url = new URL(iPath);
                        // 打开输入流
                        InputStream inputStream = url.openStream();
                        // 对网上资源进行下载转换位图图片
                        bitmaps[i] = BitmapFactory.decodeStream(inputStream);
                        saveBitmap(bitmaps[i], i + ".jpg");
                        inputStream.close();
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
//                handler.sendEmptyMessage(1);
            }

        }).start();
    }

//    //使用handler更新UI
//    Handler handler = new Handler() {
//        public void handleMessage(Message msg) {
//            if (msg.what == 1) {
//                BitmapUtil.getInstance().setBitmaps(bitmaps);
//                Intent intent = new Intent(mContext, StartUpActivity.class);
//                startActivity(intent);
//                appFinish();
//            }
//        }
//    };

    private Bitmap getBitmap(String name) {
        File appDir = new File(Environment.getExternalStorageDirectory(), "archstoday");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = name;
        File file = new File(appDir, fileName);

        return BitmapFactory.decodeFile(String.valueOf(file));
    }

    private void saveBitmap(Bitmap bmp, String name) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "archstoday");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = name;
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
